package de.ubschmidt.capi.util;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 *
 */
public final class ByteBufferFactory {

    /** Byte order within CAPI messages is always little endian. */
    private static final ByteOrder BYTE_ORDER = ByteOrder.LITTLE_ENDIAN;

    /** A capacity of 1024 byte is sufficient for all CAPI 2.0 messages. */
    private static final int DEFAULT_CAPACITY = 1024;

    private ByteBufferFactory() {
    }

    /**
     * Allocate a {@code ByteBuffer} of default capacity (1024)
     * and little endian byte order.
     *
     * @return A little endian {@code ByteBuffer} of default capacity (1024).
     */
    public static ByteBuffer allocate() {
        return allocate(DEFAULT_CAPACITY);
    }

    /**
     * Allocate a little endian {@code ByteBuffer} of the specified capacity.
     *
     * @see ByteBuffer.allocate(int)
     *
     * @param capacity Capacity of the {@code ByteBuffer}.
     *
     * @return A ByteBuffer of the specified capacity and an initial byte
     *         order of LITTE_ENDIAN.
     */
    public static ByteBuffer allocate(final int capacity) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(capacity);
        byteBuffer.order(BYTE_ORDER);

        return byteBuffer;
    }

    /**
     * Wrap the specified byte array in a little endian {@code ByteBuffer}.
     *
     * @see ByteBuffer.wrap(byte [])
     *
     * @param buf
     * @return
     */
    public static ByteBuffer wrap(final byte [] buf) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(buf);
        byteBuffer.order(BYTE_ORDER);

        return byteBuffer;
    }

}
